using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using WinRT.Interop;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Pickers;
using Windows.Storage;
using DevCangjie.Pages.EditPage;
using DevCangjie.utils.Settings;
using System.Collections.Generic;
using DevCangjie.utils.CommandRunner;
using Windows.ApplicationModel;
using Windows.Storage.Streams;
using UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding;
using DevCangjie.Pages.ConsolePage;
using DevCangjie.Pages.SettingsPage;
using DevCangjie.Pages.MessagePage;
using static DevCangjie.utils.Settings.Settings;
using System.Linq;

namespace DevCangjie
{
    public class TabData
    {
        public string Header { get; set; }
        public string FilePath { get; set; } // 使用文件路径打开
        // 如果标签页是新建的（未保存），可以使用内容字符串
        public string Content { get; set; }
        public bool IsFromFile => !string.IsNullOrEmpty(FilePath);
    }

    public sealed partial class MainWindow : Window
    {
        public static IntPtr myWhnd;
        public static MainWindow Current { get; private set; }

        public MainWindow()
        {
            this.InitializeComponent();
            this.ExtendsContentIntoTitleBar = true;

            if (Settings.Instance.IsWelcomePageShown)
            {
                AddNewMessagePageTab("欢迎");
            }

            // 获取 AppWindow 实例
            var hwnd = WindowNative.GetWindowHandle(this);
            var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
            AppWindow appWindow = AppWindow.GetFromWindowId(windowId);

            // 订阅窗口关闭事件
            appWindow.Closing += AppWindow_Closing;
            SetTitleBar(AppTitleBar);

            myWhnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
            Current = this;
            UpdateCurrentTheme(Application.Current.RequestedTheme);
            ConsolePage.AppendInfoOutput("DevCangjie initialization success.");


        }

        private async void OpenTab_Click(object sender, RoutedEventArgs e)
        {
            // 创建文件选择器
            var picker = new FileOpenPicker();

            // 设置文件选择器的起始位置（可选）
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

            // 添加支持的文件类型（根据需要调整）
            picker.FileTypeFilter.Add("*");

            // 获取当前窗口句柄
            var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
            WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);

            // 显示文件选择对话框
            StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                // 创建新的标签页
                AddNewEditPageTab(file.Name, file);

            }
            else
            {
                // 用户取消选择
                // 可选：显示提示或执行其他操作
            }
        }

        private async void TabView_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args)
        {
            if (args.Tab.Content is EditPage editPage)
            {
                if (!editPage.IsSaved)
                {
                    // 提示用户是否保存更改
                    var saveDialog = new ContentDialog()
                    {
                        Title = "保存文件",
                        Content = $"您要保存对 \"{args.Tab.Header}\" 的更改吗？",
                        PrimaryButtonText = "保存",
                        SecondaryButtonText = "不保存",
                        CloseButtonText = "取消",
                        DefaultButton = ContentDialogButton.Primary,
                        XamlRoot = this.Content.XamlRoot,
                    };

                    var result = await saveDialog.ShowAsync();
                    if (result == ContentDialogResult.Primary)
                    {
                        await editPage.SaveAsync(this);
                    }
                    else if (result == ContentDialogResult.None)
                    {
                        return;
                    }
                }
            }
            sender.TabItems.Remove(args.Tab);
        }

        private void NewTab_Click(object sender, RoutedEventArgs e)
        {
            AddNewEditPageTab("无标题", "");
        }

        private void OnEditTabViewGridSizeChanged(object sender, SizeChangedEventArgs e)
        {
            // 根据需要处理大小变化
            var gridView = (Grid)sender;
            tabView.Height = gridView.ActualHeight;
        }
        private void OnConsoleViewGridSizeChanged(object sender, SizeChangedEventArgs e)
        {
            // 根据需要处理大小变化
            var gridView = (Grid)sender;
            ConsolePage.Height = gridView.ActualHeight;
            ConsolePage.Width = gridView.ActualWidth;
        }

        public void RefreshUIStyles()
        {
            // 更新所有打开的编辑器标签页的样式
            foreach (var item in tabView.TabItems)
            {
                if (item is TabViewItem tabViewItem && tabViewItem.Content is Page page)
                {
                    if (page is EditPage editPage)
                    {
                        // 调用编辑器页面的 ApplySettings 方法
                        editPage.ApplySettings();
                    }
                }
            }

            // 更新控制台页面的样式
            if (ConsolePage != null)
            {
                ConsolePage.Instance.ApplySettings();
            }
        }

        private void AddNewEditPageTab(string header, StorageFile path)
        {
            var newTab = new TabViewItem
            {
                Header = header,
                Content = new EditPage(path)
            };
            tabView.TabItems.Add(newTab);

            // 将新标签页设置为选中状态
            tabView.SelectedItem = newTab;
        }
        private void AddNewEditPageTab(string header, string content)
        {
            var newTab = new TabViewItem
            {
                Header = header,
                Content = new EditPage(content)
            };
            tabView.TabItems.Add(newTab);

            // 将新标签页设置为选中状态
            tabView.SelectedItem = newTab;
        }

        public void SetActivePage(Page page)
        {
            if (page == null)
            {
                return;
            }

            foreach (var item in tabView.TabItems)
            {
                if (item is TabViewItem tabViewItem && ReferenceEquals(tabViewItem.Content, page))
                {
                    tabView.SelectedItem = tabViewItem;
                    return;
                }
            }
        }

        private void AddNewMessagePageTab(string header)
        {
            var newTab = new TabViewItem
            {
                Header = header,
                Content = new MessagePage()
            };
            tabView.TabItems.Add(newTab);
            // 将新标签页设置为选中状态
            tabView.SelectedItem = newTab;
        }

        private void AddNewSettingsPageTab(string selectTag = "")
        {
            // 在 tabView.TabItems 中查找 Content 为 SettingsPage 的 TabViewItem
            foreach (var item in tabView.TabItems)
            {
                if (item is TabViewItem tabViewItem && tabViewItem.Content is SettingsPage)
                {
                    tabView.SelectedItem = tabViewItem;

                    if (!string.IsNullOrEmpty(selectTag))
                    {
                        if (tabViewItem.Content is SettingsPage settingsPage)
                        {
                            settingsPage.SelectMenuItem(selectTag);
                        }
                    }
                    return;
                }
            }

            // 未找到设置标签页，创建新的
            var settingsPageInstance = new SettingsPage();
            var newTab = new TabViewItem
            {
                Header = "设置",
                Content = settingsPageInstance
            };
            // 插入到第一位
            tabView.TabItems.Insert(0, newTab);

            // 将新创建的设置标签页设为选中
            tabView.SelectedItem = newTab;

            if (!string.IsNullOrEmpty(selectTag))
            {
                settingsPageInstance.SelectMenuItem(selectTag);
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            //保存文件
            var tab = tabView.SelectedItem as TabViewItem;
            if (tab == null)
            {
                // 未选中标签页
                // 可选：显示提示或执行其他操作
                return;
            }
            var editPage = tab.Content as EditPage;
            if (editPage != null)
            {
                editPage.SaveAsync(this);
                return;
            }

        }

        private async void SaveAs_Click(object sender, RoutedEventArgs e)
        {
            // 保存文件
            var tab = tabView.SelectedItem as TabViewItem;
            if (tab == null)
            {
                // 未选中标签页
                // 可选：显示提示或执行其他操作
                return;
            }
            var editPage = tab.Content as EditPage;
            if (editPage != null)
            {
                await editPage.SaveAsAsync(this);
                return;
            }
        }

        private async void SaveAll_Click(object sender, RoutedEventArgs e)
        {
            // 保存所有文件
            foreach (TabViewItem tab in tabView.TabItems)
            {
                var editPage = tab.Content as EditPage;
                if (editPage != null)
                {
                    // 检查文件是否有保存路径
                    if (string.IsNullOrEmpty(editPage.FilePath))
                    {
                        // 将当前标签页设置为选中状态
                        tabView.SelectedItem = tab;

                        // 如果没有保存路径，则执行“另存为”
                        await editPage.SaveAsAsync(this);
                    }
                    else
                    {
                        // 如果有保存路径，则直接保存
                        await editPage.SaveAsync(this);
                    }
                }
            }
        }

        private void FindReplace_Click(object sender, RoutedEventArgs e)
        {
            if (tabView.SelectedItem is TabViewItem selectedTab)
            {
                if (selectedTab.Content is EditPage editPage)
                {
                    editPage.ShowFindReplaceWindow();
                }
            }
            else
            {
                // 可选：提示未打开任何编辑页面
            }
        }


        private async void Compile_Click(object sender, RoutedEventArgs e)
        {
            var compileButton = sender as Button;
            if (compileButton != null)
            {
                compileButton.IsEnabled = false;
            }

            try
            {
                // 获取当前选中的标签页
                var tab = tabView.SelectedItem as TabViewItem;
                if (tab == null)
                {
                    // 未选中标签页
                    ConsolePage.AppendErrorOutput("未选中任何标签页！");
                    return;
                }

                // 寻找标签页对应的 EditPage
                var editPage = tab.Content as EditPage;
                if (editPage != null)
                {
                    await editPage.CompileAsync();
                }
            }
            catch (Exception ex)
            {
                ConsolePage.AppendErrorOutput($"编译过程中发生异常: {ex.Message}");
            }
            finally
            {
                if (compileButton != null)
                {
                    compileButton.IsEnabled = true;
                }
            }
        }

        private void Run_Click(object sender, RoutedEventArgs e)
        {
            // 获取当前选中的标签页
            var tab = tabView.SelectedItem as TabViewItem;
            if (tab == null)
            {
                ConsolePage.AppendErrorOutput("没有文件可运行，请先选择一个文件！");
                return;
            }
            // 寻找标签页对应的 EditPage
            var editPage = tab.Content as EditPage;
            if (editPage != null)
            {
                _ = editPage.RunAsync();
            }
        }

        private void Debug_Click(object sender, RoutedEventArgs e)
        {
            // 获取当前选中的标签页
            var tab = tabView.SelectedItem as TabViewItem;
            if (tab == null)
            {
                ConsolePage.AppendErrorOutput("没有文件可调试，请先选择一个文件！");
                return;
            }
            // 寻找标签页对应的 EditPage
            var editPage = tab.Content as EditPage;
            if (editPage != null)
            {
                // _ = editPage.DebugAsync();
            }
        }

        private void CompileAndRun_Click(object sender, RoutedEventArgs e)
        {
            // 获取当前选中的标签页
            var tab = tabView.SelectedItem as TabViewItem;
            if (tab == null)
            {
                ConsolePage.AppendErrorOutput("没有文件可编译和运行，请先选择一个文件！");
                return;
            }
            // 寻找标签页对应的 EditPage
            var editPage = tab.Content as EditPage;
            if (editPage != null)
            {
                _ = editPage.CompileAndRunAsync();
            }
        }
        private async void Exit_Click(object sender, RoutedEventArgs e)
        {
            // 创建一个列表，存储需要关闭的标签页
            var tabsToClose = new List<TabViewItem>();

            // 遍历所有标签页
            foreach (TabViewItem tab in tabView.TabItems)
            {
                var editPage = tab.Content as EditPage;
                if (editPage != null && !editPage.IsSaved)
                {
                    // 将当前标签页设置为选中状态
                    tabView.SelectedItem = tab;

                    if (editPage != null && !editPage.IsSaved)
                    {
                        // 提示用户是否保存更改
                        var saveDialog = new ContentDialog()
                        {
                            Title = "保存文件",
                            Content = $"您要保存对 \"{tab.Header}\" 的更改吗？",
                            PrimaryButtonText = "保存",
                            SecondaryButtonText = "不保存",
                            CloseButtonText = "取消",
                            DefaultButton = ContentDialogButton.Primary,
                            XamlRoot = this.Content.XamlRoot,
                        };

                        var result = await saveDialog.ShowAsync();
                        if (result == ContentDialogResult.Primary)
                        {
                            // 用户选择保存
                            string filePath = editPage.FilePath;
                            if (string.IsNullOrEmpty(filePath))
                            {
                                await editPage.SaveAsAsync(this);
                            }
                            else
                            {
                                await editPage.SaveAsync(this);
                            }
                            tabsToClose.Add(tab);
                        }
                        else if (result == ContentDialogResult.Secondary)
                        {
                            // 用户选择不保存
                            tabsToClose.Add(tab);
                            continue;
                        }
                        else
                        {
                            // 用户取消操作，停止退出流程
                            return;
                        }
                    }
                    else
                    {
                        // 文件已保存或无修改
                        tabsToClose.Add(tab);
                    }
                }
            }

            // 关闭所有标签页
            foreach (var tab in tabsToClose)
            {
                tabView.TabItems.Remove(tab);
            }

            // 退出程序
            Application.Current.Exit();
        }

        private void AppWindow_Closing(AppWindow sender, AppWindowClosingEventArgs e)
        {
            // 取消默认关闭操作
            e.Cancel = true;

            // 调用 Exit_Click 方法
            Exit_Click(sender, null);
        }

        private void CloseAllTabs_Click(object sender, RoutedEventArgs e)
        {
            // 关闭所有标签页
            tabView.TabItems.Clear();
        }

        private void AddTab_Click(TabView sender, object Object)
        {
            AddNewEditPageTab("无标题", "");
        }

        private void SettingsTab_Click(object sender, RoutedEventArgs e)
        {
            AddNewSettingsPageTab();
        }
        /// <summary>
        /// 根据 ElementTheme 更新 Settings.CurrentTheme
        /// </summary>
        /// <param name="theme">当前元素的主题</param>
        private void UpdateCurrentTheme(ApplicationTheme theme)
        {
            switch (theme)
            {
                case ApplicationTheme.Light:
                    Settings.Instance.UpdateTheme(Theme.Light);
                    break;
                case ApplicationTheme.Dark:
                    Settings.Instance.UpdateTheme(Theme.Dark);
                    break;
                default:
                    // 默认使用浅色主题
                    Settings.Instance.UpdateTheme(Theme.Light);
                    break;
            }
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            AddNewSettingsPageTab("AboutOption");
        }
    }
}
